import {Input, InputNumber} from 'antd'
import React, {useState} from 'react'
import css from './index.module.less'

export default function InputSimple(props) {
  const {value, onChange, type, disabled, readonly} = props
  const ref = React.useRef()
  const [val, setVal] = useState(value)
  const [res, setRes] = useState()

  React.useEffect(() => {
    if (value !== val) {
      setVal(value)
      if (value) {
        setRes(value)
      }
    }
  }, [value])

  // 输入框输入
  function handleChange(e) {
    let val = e?.target?.value ?? e
    setVal(val)
    setRes(val)
  }

  // 输入框回车
  function handlePressEnter() {
    onChange(res)
  }

  // 输入框失去焦点
  function handleBlur() {
    onChange(res)
  }

  function renderInput() {
    let ele = ''
    switch (type) {
      case 'number':
        ele = <InputNumber
          ref={ref}
          className={css.iptNum}
          variant="borderless"
          disabled={disabled}
          value={val}
          min={0}
          controls={false}
          onBlur={handleBlur}
          onChange={handleChange}
          onPressEnter={handlePressEnter}
        />
        break
      default:
        ele = <Input
          ref={ref}
          disabled={disabled}
          variant="borderless"
          value={val}
          onBlur={handleBlur}
          onChange={handleChange}
          onPressEnter={handlePressEnter}
        />
        break
    }

    return ele
  }

  return <div className={css.ipt}>
    {readonly ? val : renderInput()}
  </div>
}